﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using CaiyinSoft.NetGather.Protocol;

namespace CaiyinSoft.NetGather.NetGatherLib.Filter.Process
{
    [Serializable]
    public class FileDownloadHTMLFilter: HTMLFilterBase
    {
        
        public override string FilterCaption
        {
            get
            {
                return "文件下载过滤器";
            }
        }

        public override string ExpressionCaption
        {
            get
            {
                return "";
            }
        }

        public override string Description
        {
            get
            {
                return "把指定文件下载";
            }
        }

        
        public string SavePath { get;  set; }
        public FileDownloadHTMLFilter()
            : base()
        {
            _InitParams();
        }

        private void _InitParams()
        {
            SetInputHTML("");
            OutputKey = Guid.NewGuid().ToString();
            SavePath = "";
        }

        public override List<FilterResult> FilterHTML()
        {
            int parentHTMLPosition = 0;
            if (ParentFilter != null)
                parentHTMLPosition = ParentFilter.HTMLPosition;
            HTMLPosition = parentHTMLPosition;

            List<FilterResult> parentResults = GetInputHTML();
            if (parentResults == null || parentResults.Count == 0) return null;
            List<FilterResult> listRevalue = new List<FilterResult>();

            foreach (var pr in parentResults)
            {
                string ext = string.Empty;
                int lastIndex = pr.HTMLResult.LastIndexOf("/");
                if (lastIndex > 0)
                {
                    string fn = pr.HTMLResult.Substring(lastIndex + 1);
                    ext = System.IO.Path.GetExtension(fn);
                }

                if (string.IsNullOrEmpty(ext) || ext.Length == 0)
                {
                    ext = ".jpg";
                }

                DateTime dt = DateTime.Now;
                string fileName = string.Format("{0}/{1}/{2}/{3}{4}",
                    dt.Year,
                    dt.Month.ToString().PadLeft(2, '0'),
                    dt.Day.ToString().PadLeft(2, '0'),
                    Guid.NewGuid().ToString(),
                    ext);

                downloadFile(pr.HTMLResult, fileName);
                FilterResult result = new FilterResult(pr.HTMLPosition, fileName);
                listRevalue.Add(result);
            }
            return listRevalue; // 

        }

        private bool downloadFile(string url,string fileName)
        {


            string fn2 = System.IO.Path.Combine(SavePath, fileName );

            System.IO.FileInfo fi = new System.IO.FileInfo(fn2);
            if (!System.IO.Directory.Exists(fi.Directory.FullName))
                System.IO.Directory.CreateDirectory(fi.Directory.FullName);

            WebClient client = new WebClient();
            try
            {
                client.DownloadFile(url, fn2);
                return true;
            }
            catch
            {
                return false;
            }

        }


        public override IHTMLFilter Clone()
        {

            FileDownloadHTMLFilter filter = new FileDownloadHTMLFilter();
            foreach (var f in this.ChildFilters)
            {
                var fc = f.Clone();
                fc.ParentFilter = filter;
                filter.ChildFilters.Add(fc);
            }
            filter.Runabled = this.Runabled;
            filter.RunOnce = this.RunOnce;
            filter.OutputKey = this.OutputKey;
            filter.FilterExpression = this.FilterExpression;

            filter.SavePath = this.SavePath;
            return filter;
        }

        [NonSerialized]
        private P004_FileDownloadHTMLFilterForm _editform;
        public override InnerFormBase GetEditForm()
        {
            if (_editform == null)
            {
                _editform = new P004_FileDownloadHTMLFilterForm();
                _editform.InfoSaveEventHandler += (sender, args) =>
                {
                    this.RunOnce = _editform.RunOnce;
                    this.OutputKey = _editform.OutputKey;
                    this.SavePath = _editform.SavePath;
                };
            }
            _editform.HTMLFilter = this;
            return _editform;
        }
    }


}
